import React, { useState,useEffect ,useCallback} from 'react'
import request,{ baseUrl }  from '@/utils/request'
import { message, Table, Image, Button, Space, Tag, Row, Col, Popconfirm } from 'antd'
import { DeleteOutlined, FormOutlined, PlusOutlined, FileImageOutlined, ToTopOutlined } from '@ant-design/icons'
import { useNavigate, useSearchParams } from 'react-router-dom'

const List = () => {

    const [urlParams, setUrlParams] = useSearchParams()
    const [params, setParams] = useState({
        // 解决数据类型为string引起的bug
        page: Number(urlParams.get('page')) || 1,
        size: Number(urlParams.get('size')) || 10
    })
    const [total, setTotal] = useState(0)
    const navigate = useNavigate();


    let controller
    const [orderList,setOrederList] = useState([]);
    //获取订单列表
    const getOrderList = async() => {
        controller = new AbortController()
        const {data} = await request.get('/order/list',{
            params,
            signal: controller.signal
        })
        if(data.code == 200){
            setOrederList(data.data)
            setTotal(data.total)
        }
    }

    console.log('订单',orderList);
    const columns = [
        {
            title: '#',
            key: '_id',
            width: 10,
            render(text, record, index) {
                return index + 1
            }
        },
        {
            title: '订单号',
            dataIndex: 'order_num',
            width: 80,
            //自定义单元格内容
            render: (text, record, index) => {
                // text: 当前列数据(dataIndex对应的数据，如无dataIndex,text与record一致)
                // record: 当前行数据
                // index: 当前索引值
                // console.log(text, record, index)
                return <h4>{text}</h4>
            }
        },
        {
            title: '订单金额',
            dataIndex: 'count_price',
            width: 100,
            render(text, item) {
                return (
                    <>
                        <p className='price'>
                            <span>￥{text}</span>
                        </p>
                    </>
                )
            }
        },
        {
            title: '订单状态',
            dataIndex: 'complete',
            width:100,
            render(text, item) {
                return (
                    <>
                        <h4>{text==1 ? "已完成" : "进行中"}</h4>
                    </>
                )
            }
        },
        {
            title: '用户名',
            dataIndex: 'username',
            render(text, item) {
                return (
                    <>
                        <h4>{text}</h4>
                    </>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'Oid',
            width: 100,
            render(id) {
                return (
                    // <React.Fragment>
                    <Space>
                        <Button ghost type='primary' icon={<FormOutlined />} size="small" onClick={editItem.bind(null, id)}></Button>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItem.bind(null, id)}
                        >
                            <Button danger icon={<DeleteOutlined />} size="small"></Button>

                        </Popconfirm>
                    </Space>
                )
            }
        },
    ]

    const [selectIds, setSelectIds] = useState([])
    // 商品操作CRUD
    const removeItem = useCallback(async (Oid) => {
        const { data } = await request.post('/order/delData', { Oid })
        if (data.code === 200) {
            message.success('订单删除成功')
            // 刷新页面方案一：重新请求数据
            getOrderList()

            // 刷新页面方案二：修改state达到刷新的效果
            // setDatalist(datalist.filter(item=>item._id != id))
        }
    }, [orderList])
    const removeItems = useCallback(async () => {
        if (selectIds.length === 0) {
            return message.warning('请选择删除的订单');
        }
        const { data } = await request.post('/order/delSome', {
            // headers: {
            //     Authorization: userInfo.authorization
            // },
            ids: selectIds

        })

        if (data.code === 200) {
            message.success('订单删除成功')
            getOrderList()
        }
    }, [selectIds])
    const addItem = useCallback(() => {
        navigate('/manage/order/add')
    }, [])
    const editItem = useCallback((id) => navigate('/manage/order/' + id), [])

    const rowSelection = {
        onChange(selectedRowKeys) {
            console.log('selectedRowKeys=', selectedRowKeys)
            setSelectIds(selectedRowKeys)
        }
    }
    const pagination = {
        total,
        current: params.page,
        pageSize: params.size,
        size: 'small',
        onChange(page, size) {
            setParams({
                page,
                size
            })

            setUrlParams({
                page,
                size
            })
        }
    }

    useEffect(() => {
        getOrderList();

        return function () {
            // 取消ajax
            controller.abort()
        }
    }, [params])
    return (
        <div>
            <Row gutter={20}>
                <Col span={8}>
                    <Button type='primary' icon={<PlusOutlined />} onClick={addItem}>添加</Button>
                </Col>
                <Col span={16} className='text-right'>

                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItems}
                        >
                            <Button danger icon={<DeleteOutlined />}>批量删除</Button>

                        </Popconfirm>
                </Col>
            </Row>
            <Table
                style={{ marginTop: 20 }}
                rowKey="Oid"
                rowSelection={rowSelection}
                columns={columns}
                dataSource={orderList}
                pagination={pagination}
            />
        </div>
    )
}


export default List;